<template>
  <div>
    <el-row>
      <el-form :model="requestParams"
               label-width="80px"
               :rules="rules"
               ref="form">
        <el-col :span="24">
          <el-form-item label="新闻标题"
                        prop="title">
            <el-input v-model="requestParams.title"
                      placeholder="请输入新闻标题"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="新闻图片"
                        prop="imgs">
            <el-upload :http-request="uploadFile"
                       action=""
                       list-type="picture-card"
                       :on-preview="handlePictureCardPreview"
                       :on-remove="handleRemove"
                       :before-upload="beforeAvatarUpload"
                       :file-list="requestParams.imgs"
                       accept=".jpg,.png,.jpeg">
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible"
                       :modal-append-to-body="false"
                       :append-to-body="true">
              <img width="100%"
                   :src="dialogImageUrl"
                   alt="">
            </el-dialog>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="新闻封面"
                        prop="newsCover_imgs">
            <el-upload :http-request="uploadFile2"
                       action=""
                       list-type="picture-card"
                       :on-preview="handlePictureCardPreview2"
                       :on-remove="handleRemove2"
                       :before-upload="beforeAvatarUpload2"
                       :file-list="requestParams.newsCover_imgs"
                       accept=".jpg,.png,.jpeg">
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible2"
                       :modal-append-to-body="false"
                       :append-to-body="true">
              <img width="100%"
                   :src="dialogImageUrl2"
                   alt="">
            </el-dialog>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="新闻时间"
                        prop="news_date">
            <el-date-picker v-model="requestParams.news_date"
                            align="right"
                            type="date"
                            value-format="yyyy-MM-dd hh:mm:ss"
                            placeholder="选择日期"
                            :picker-options="pickerOptions">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="新闻正文"
                        prop="content">
            <EditorModify :todosc="todosc"
                          :catchData="catchData"
                          :verData="verData"></EditorModify>
          </el-form-item>
        </el-col>
        <el-col :span="24"
                class="bot-style">
          <el-button type="primary"
                     v-if="todos=== 1 || todos ===2"
                     size="medium"
                     @click="onSave('form')">保存</el-button>
          <el-button size="medium"
                     @click="onBack">取消</el-button>
        </el-col>
      </el-form>
    </el-row>
  </div>
</template>

<script>
// import { editUnitApi } from '@/services/orgainzeManage'
// import Editor from './Editor'

// import { CulManagePartyBuildApi } from '@/services/WorkCenter'
import { UploadFileApi } from '@/services/UserPermission'
import EditorModify from './EditorModify'
import { MessageCenterApi } from '@/services/ProjectCenter';
import moment from 'moment'
export default {
  props: {
    todos: Number,
    catchBack: Function,
    catchSave: Function,
    objRow: String,
  },
  components: {
    EditorModify,
  },
  data () {
    return {
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now();
        },
        shortcuts: [{
          text: '今天',
          onClick (picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: '昨天',
          onClick (picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            picker.$emit('pick', date);
          }
        }, {
          text: '一周前',
          onClick (picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', date);
          }
        }]
      },
      project_id: '',
      disabled: false,
      // todosc: 0,
      todosc: '',
      dialogImageUrl: '',
      dialogVisible: false,
      dialogImageUrl2: '',
      dialogVisible2: false,
      requestParams: {
        title: '',
        news_date: '',
        imgs: [],
        newsCover_imgs:[],
        content: '',
      },
      rules: {
        title: [
          { required: true, message: '新闻标题不能为空', trigger: 'blur' }
        ],
        imgs: [
          { required: true, message: '新增图片不能为空', trigger: 'blur' }
        ],
        news_date: [
          { required: true, message: '时间不能为空', trigger: 'blur' }
        ],
      }
    }
  },
  methods: {
    beforeAvatarUpload (file) {
      return true
      // const isLt2M = file.size / 1024 / 1024 < 2;
      // if (!isLt2M) {
      //   this.$message.error('上传新闻图片大小不能超过 2MB!');
      // }
      // return isLt2M;
    },
    beforeAvatarUpload2 (file) {
      return true
      // const isLt2M = file.size / 1024 / 1024 < 2;
      // if (!isLt2M) {
      //   this.$message.error('上传新闻图片大小不能超过 2MB!');
      // }
      // return isLt2M;
    },
    uploadFile (params) {//图片上传    
      var formData = new FormData()
      formData.append('pic_file_apk', params.file)
      this.requestParams.imgs = []
      UploadFileApi.uploadFile({ data: formData }).then(
        res => {
          console.log(this.requestParams.imgs)
          this.requestParams.imgs.push({ url: res.data.file_path });
          // this.editFormData.logo =
          //   res.data.upload_success[0].absolute_url

        },
        err => {
          console.log(err)
        }
      )
    },
    uploadFile2 (params) {//图片上传    
      var formData = new FormData()
      formData.append('pic_file_apk', params.file)
      this.requestParams.imgs = []
      UploadFileApi.uploadFile({ data: formData }).then(
        res => {
          console.log(this.requestParams.newsCover_imgs)
          this.requestParams.imgs.push({ url: res.data.file_path });
          // this.editFormData.logo =
          //   res.data.upload_success[0].absolute_url

        },
        err => {
          console.log(err)
        }
      )
    },
    //详情
    getDetail () {
      console.log(JSON.parse(this.objRow));
      MessageCenterApi.getDetailList({
        params: {
          news_id: JSON.parse(this.objRow).news_id,
        }
      }).then((res) => {
        if (res.code == 0) {
          console.log(res);
          this.requestParams = res.data
        }
      }).catch((error) => {
        console.log(error)
      })

    },
    addNews (imgArr) {
      let newsId
      if (this.todos === 2) {
        newsId = JSON.parse(this.objRow).news_id
      }
      console.log();
      MessageCenterApi.saveNewsList({
        data: {
          news_id: this.todos === 1 ? '' : newsId,
          title: this.requestParams.title,
          imgs: imgArr,
          news_date: this.requestParams.news_date,
          content: this.requestParams.content,
        }
      }).then((res) => {
        if (res.code == 0) {
          if (this.todos == 1) {
            this.$message.success('新增成功')
          } else {
            this.$message.success('编辑成功')
          }
          this.catchSave();//保存
        }
      }).catch((error) => {
        console.log(error)
      })

    },
    onSave (data) {//保存
      this.$refs[data].validate((valid) => {
        if (valid) {
          var imgArr = []
          if (this.requestParams.imgs.length > 0) {
            console.log(this.requestParams.imgs.length);
            this.requestParams.imgs.forEach(ele => {
              let img = {
                url: ele.url
              }
              imgArr.push(img)
            })
          };
          this.addNews(imgArr)//新增/编辑
        } else {
          return false;
        }
      })
    },
    onReset () {//重置
      this.requestParams.title = '';
      this.requestParams.news_date = '';
      this.requestParams.imgs = [];
      this.requestParams.content = '';
      this.requestParams.sort = 1;
    },
    onBack () {//返回
      this.todosc = ''
      this.catchBack();//返回
      this.$refs.form.resetFields()
    },
    catchData (value) {
      console.log(value);
      this.requestParams.content = value;
      if (value == '<p><br></p>') {
        this.requestParams.content = ''
      };

    },
    verData (value) {
      // this.requestParam_add.ver_content = value;
      this.requestParams.content = value;
      if (value == '<p><br></p>') {
        this.requestParams.content = ''
      }
    },
    //删除图片
    handleRemove (file, fileList) {
      this.requestParams.imgs = fileList;
    },
      //删除新闻封面图片
      handleRemove2 (file, fileList) {
      this.requestParams.newsCover_imgs = fileList;
    },
    //预览图片
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
     //预览新闻封面图片
     handlePictureCardPreview2 (file) {
      this.dialogImageUrl2 = file.url;
      this.dialogVisible2 = true;
    }
  },
  watch: {
    '$store.state.choosedProject.project_id': function (val) {
      this.project_id = val;

    },
    // todos (n, o) {
    //   console.log(n);
    //   console.log(152138);
    //   if (n == 2 || n == 3) {
    //     this.getDetail()
    //     // this.requestParams = JSON.parse(this.objRow);
    //     console.log(this.requestParams.title);
    //     // this.requestParams.title = JSON.parse(this.objRow).title;
    //     // this.requestParams.news_date = moment(JSON.parse(this.objRow).news_date);
    //     this.requestParams.imgs = [];
    //     if (JSON.parse(this.objRow).imgs) {
    //       JSON.parse(this.objRow).imgs.forEach(ele => {
    //         this.requestParams.imgs.push({ url: ele })
    //       });
    //     }

    //     this.requestParams.content = JSON.parse(this.objRow).content;
    //     this.todosc = this.requestParams.content;
    //   };
    //   if (n == 0) {
    //     this.todosc = ''
    //     this.onReset();//重置
    //   }
    // }
  },
  mounted () {
    this.project_id = this.$store.state.choosedProject.project_id
    if (this.todos === 3 || this.todos === 2) {
      console.log(JSON.parse(this.objRow));
      this.requestParams.imgs = [];
      if (JSON.parse(this.objRow).imgs) {
        JSON.parse(this.objRow).imgs.forEach(ele => {
          this.requestParams.imgs.push({ url: ele })
        });
      }
      this.requestParams.content = JSON.parse(this.objRow).content;
      this.todosc = this.requestParams.content;

      this.getDetail()
    }
    console.log(this.todos);
    if (this.todos == 0) {
      this.todosc = ''
      this.onReset();//重置
    }

  }
}
</script>

<style lang="scss" scoped>
.bot-style {
  text-align: center;
  margin-top: 20px;
}
.el-date-editor,
.el-select {
  width: 100%;
}
</style>